import { apiRequest } from './request'
import axios from 'axios'

// 种母配种的API请求基础URL配置
// 从环境变量或配置文件中获取，避免硬编码
const API_CONFIG = {
  READ_API: import.meta.env.VITE_SHEEP_BREEDING_READ_API || 'http://39.96.200.62:8411',
  WRITE_API: import.meta.env.VITE_SHEEP_BREEDING_WRITE_API || 'http://39.96.200.62:8511',
  BASE_PATH: '/api/EweMating'
}

// 读API实例 - 用于查询操作
const readApi = axios.create({
  baseURL: API_CONFIG.READ_API,
  timeout: 10000
})

// 写API实例 - 用于新增、修改、删除操作
const writeApi = axios.create({
  baseURL: API_CONFIG.WRITE_API,
  timeout: 10000
})

// 为API实例添加Token
readApi.interceptors.request.use(config => {
  const token = localStorage.getItem('Token') || localStorage.getItem('token')
  if (token && config.headers) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

writeApi.interceptors.request.use(config => {
  const token = localStorage.getItem('Token') || localStorage.getItem('token')
  if (token && config.headers) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

/**
 * 分页查询种母配种列表
 * @param params 查询参数
 * @returns 分页结果
 */
export function getEweMatingList(params: {
  breedingDateStart?: string | null;
  breedingDateEnd?: string | null;
  earNumber?: string;
  principal?: string;
  pageIndex: number;
  pageSize: number;
  sortField?: string;
  sortOrder?: 'asc' | 'desc';
}) {
  return readApi.post(`${API_CONFIG.BASE_PATH}/paging`, params);
}

/**
 * 获取所有种母配种信息 - 使用GET方法
 * 这是getEweMatingList的备选实现，使用GET方法
 */
export function getEweMatingListByGet(params: {
  breedingDateStart?: string | null;
  breedingDateEnd?: string | null;
  earNumber?: string;
  principal?: string;
  pageIndex: number;
  pageSize: number;
  sortField?: string;
  sortOrder?: 'asc' | 'desc';
}) {
  // 处理参数，移除null和undefined值，防止传递无效参数
  const queryParams: Record<string, any> = {};
  
  // 只添加有值的参数
  if (params.pageIndex !== undefined) queryParams.pageIndex = params.pageIndex;
  if (params.pageSize !== undefined) queryParams.pageSize = params.pageSize;
  if (params.earNumber) queryParams.earNumber = params.earNumber;
  if (params.principal) queryParams.principal = params.principal;
  if (params.breedingDateStart) queryParams.breedingDateStart = params.breedingDateStart;
  if (params.breedingDateEnd) queryParams.breedingDateEnd = params.breedingDateEnd;
  if (params.sortField) queryParams.sortField = params.sortField;
  if (params.sortOrder) queryParams.sortOrder = params.sortOrder;
  
  return readApi.get(`${API_CONFIG.BASE_PATH}`, { params: queryParams });
}

/**
 * 根据配种编号获取种母配种详情
 * @param breedingId 配种编号
 * @returns 种母配种详情
 */
export function getEweMatingDetail(breedingId: string) {
  return readApi.get(`${API_CONFIG.BASE_PATH}/${breedingId}`);
}

/**
 * 获取种母配种明细
 * @param breedingId 配种编号
 * @returns 种母配种明细列表
 */
export function getEweMatingDetailsList(breedingId: string) {
  return readApi.get(`${API_CONFIG.BASE_PATH}/${breedingId}/details`);
}

/**
 * 获取所有种母配种信息
 * @returns 所有种母配种信息列表
 */
export function getEweMatingOwning() {
  return readApi.get(`${API_CONFIG.BASE_PATH}/owning`);
}

/**
 * 添加新的种母配种信息
 * @param data 种母配种数据
 * @returns 操作结果
 */
export function addEweMating(data: any) {
  console.log('提交新增数据:', JSON.stringify(data));
  return writeApi.post(`${API_CONFIG.BASE_PATH}`, data);
}

/**
 * 更新种母配种信息
 * @param data 种母配种数据
 * @returns 操作结果
 */
export function updateEweMating(data: any) {
  console.log('提交更新数据:', JSON.stringify(data));
  return writeApi.put(`${API_CONFIG.BASE_PATH}`, data);
}

/**
 * 删除种母配种信息
 * @param breedingId 配种编号
 * @returns 操作结果
 */
export function deleteEweMating(breedingId: string) {
  return writeApi.delete(`${API_CONFIG.BASE_PATH}/${breedingId}`);
}

/**
 * 批量添加种母配种信息
 * @param data 批量配种数据，字段与后端接口一致
 * @returns 操作结果
 */
export function batchAddEweMating(data: {
  earNumbers: string[],
  breedingDate: string,
  lastBreedingDate?: string,
  femaleBreed: string,
  firstMaleSheep: string,
  extraMaleSheep: string,
  breedingMethod: string,
  femaleEstrusType: string,
  firstBreedingScore: string,
  breedingScore: number,
  breedingHouse: string,
  breedingPen: string,
  transferHouse: string,
  breedingStatus: string,
  eventDate: string,
  principal: string,
  remark: string,
  creator: string,
  weight: number
}) {
  return writeApi.post(`${API_CONFIG.BASE_PATH}/batch`, data);
}